package com.ljm.filter;


import com.ljm.security.TokenManager;
import com.ljm.service.UserService;
import com.ljm.utils.R;
import com.ljm.utils.ResponseUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 访问过滤器
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    @Autowired
    UserService userService;

    public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        super(authManager);
        System.out.println("authManager ====== "+authManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        logger.info("URL ================="+req.getRequestURI());

        System.out.println("Request token == "+req.getHeader("token"));
        System.out.println("response token == "+res.getHeader("token"));
        System.out.println("response getHeaderNames == "+res.getHeaderNames());
        System.out.println("Request Authorization == "+req.getHeader("Authorization"));
        System.out.println("response Authorization == "+res.getHeader("Authorization"));
        logger.info("URL userEntity ================="+req.getRequestURI().indexOf("userEntity"));
        logger.info("URL login ================="+req.getRequestURI().indexOf("login"));
        Object data =res.getHeader("Authorization");
        req.setAttribute("Authorization",data);
        // req.getRequestURI().indexOf("XXX") === 请求连接中出现   （"XXX"） 字段的次数   -1 表示不出现
//        if(req.getRequestURI().indexOf("login")==-1){
            if(req.getRequestURI().indexOf("userEntity") == -1) {
                System.out.println(" authentication  (\"userEntity\") == -1");
                chain.doFilter(req, res);
                return;
            }
//
//        }response Authorization
        String authorization = res.getHeader("Authorization");
        UsernamePasswordAuthenticationToken authentication = null;
        try {
            System.out.println("req =====  getAuthentication "+ authorization);
            authentication = getAuthentication(req);
        } catch (Exception e) {
            System.out.println(" authentication  赋值出错");
            ResponseUtil.out(res, R.error());
        }
        ///   authentication  用户名密码认证令牌 == NULL  登录成功 令牌还是为null
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            System.out.println(" authentication 为 null ");
            ResponseUtil.out(res, R.error());
        }
        System.out.println("authentication ====== "+authentication);
        chain.doFilter(req, res);
    }

//    private UsernamePasswordAuthenticationToken getAuthentication(String authorization) {
//        //System.out.println("request token == "+request.getHeader("Authorization"));
//        System.out.println("token ====== getAuthentication "+authorization);
//        if (authorization != null && !"".equals(authorization.trim())) {
//            //获取用户名称
//            String userName = tokenManager.getUserFromToken(authorization);
//            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
//            Collection<GrantedAuthority> authorities = new ArrayList<>();
//            // 返回  UsernamePasswordAuthenticationToken（用户名，密码 ，权限  ）
//            for(String permissionValue : permissionValueList) {
//                if(StringUtils.isEmpty(permissionValue)) continue;
//                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
//                authorities.add(authority);
//            }
//            System.out.println("permissionValueList === "+authorities);
//            if (!StringUtils.isEmpty(userName)) {
//                return new UsernamePasswordAuthenticationToken(userName, authorization, authorities);
//            }
//            return null;
//        }
//        return null;
//    }
//,HttpServletResponse response
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        /*  在登录过滤器 中成功返回的 token  ==null
         */
        // token置于header里
        System.out.println("request === "+request.toString());
      String token = request.getHeader("Authorization");

       // String token = (String) request.getAttribute("Authorization");
        //System.out.println("request token == "+request.getHeader("Authorization"));
        System.out.println("token ====== "+token);
        if (token != null && !"".equals(token.trim())) {
            //获取用户名称
            String userName = tokenManager.getUserFromToken(token);
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            // 返回  UsernamePasswordAuthenticationToken（用户名，密码 ，权限  ）
            for(String permissionValue : permissionValueList) {
                if(StringUtils.isEmpty(permissionValue)) continue;
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                authorities.add(authority);
            }
            System.out.println("permissionValueList === "+authorities);
            if (!StringUtils.isEmpty(userName)) {
                return new UsernamePasswordAuthenticationToken(userName, token, authorities);
                //userService.getUserAuthorityMen(userFromToken)
                //return new UsernamePasswordAuthenticationToken(userName, token, userService.getUserAuthorityMen(userName));
            }
            return null;
        }
        return null;
    }


}